package com.youdoneed.friends.lostChild;

import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import com.querydsl.sql.dml.SQLUpdateClause;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.pagination.Page;
import com.youdoneed.friends.application.QueryHelper;
import com.youdoneed.friends.common.util.FileUtil;
import com.youdoneed.friends.common.util.StringUUIdUtil;
import com.youdoneed.friends.model.LostChild;
import com.youdoneed.friends.model.LostChildClueRecord;
import com.youdoneed.friends.query.QLostChild;
import com.youdoneed.friends.query.QLostChildClueRecord;
import com.youdoneed.friends.vo.LostChildClueVo;
import com.youdoneed.friends.vo.LostChildVo;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import org.springframework.util.StringUtils;

/**
 * Created by lid on 2017/12/18 0018.
 */
@Service
@Transactional
public class LostChildService {

    private final Logger logger = LoggerFactory.getLogger(LostChildService.class);

    private final String separate = ",";

    @Autowired
    private SQLQueryFactory queryFactory;

    @Autowired
    private UserFeignClient userFeignClient;

    private QLostChild qLostChild = QLostChild.LostChild;

    private QLostChildClueRecord qLostChildClueRecord = QLostChildClueRecord.LostChildClueRecord;

    /**
     * 保存失踪儿童线索
     *
     * @param userId
     * @param lostChildId
     * @param photoUrls
     * @param message
     */
    public void insertLostChildClueRecord(String userId, String lostChildId,
                                          List<String> photoUrls, String message) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId为空");
        }

        if (!StringUtils.hasText(lostChildId)) {
            throw new AppException("lostChildId为空");
        }

        User user = userFeignClient.getUser(userId).getData();
        if (null == user) {
            throw new AppException("user为空");
        }

        LostChild lostChild = this.getLostChildDetail(lostChildId);
        if (null == lostChild) {
            throw new AppException("lostChild为空");
        }


        LostChildClueRecord record = new LostChildClueRecord();
        record.setChildId(lostChildId);
        record.setCreateDate(new Date());
        record.setMessage(message);
        record.setNo(lostChild.getNo());
        if ((photoUrls != null)
                && (0 < photoUrls.size())) {
            String photoUrl = new String();
            for(String url : photoUrls){
                photoUrl = photoUrl.concat(url).concat(this.separate);
            }
            record.setPhotoUrl(photoUrl.substring(0, photoUrl.length() - 1));
        }
        record.setRecordId(StringUUIdUtil.getUUID());
        record.setUserName(user.getName());
        record.setUserPhoneNo(user.getPhoneNo());
        record.setUserId(userId);
        queryFactory.insert(qLostChildClueRecord).populate(record).execute();
    }

    /**
     * 保存失踪儿童线索
     *
     * @param userId
     * @param lostChildId
     * @param photoUrls
     * @param message
     */
    public void saveLostChildClue(String userId, String lostChildId,
                                          String photoUrls, String message) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId为空");
        }

        if (!StringUtils.hasText(lostChildId)) {
            throw new AppException("lostChildId为空");
        }

        User user = userFeignClient.getUser(userId).getData();
        if (null == user) {
            throw new AppException("user为空");
        }

        LostChild lostChild = this.getLostChildDetail(lostChildId);
        if (null == lostChild) {
            throw new AppException("lostChild为空");
        }


        LostChildClueRecord record = new LostChildClueRecord();
        record.setChildId(lostChildId);
        record.setCreateDate(new Date());
        record.setMessage(message);
        record.setNo(lostChild.getNo());
        record.setPhotoUrl(photoUrls);
        record.setRecordId(StringUUIdUtil.getUUID());
        record.setUserName(user.getName());
        record.setUserPhoneNo(user.getPhoneNo());
        record.setUserId(userId);
        queryFactory.insert(qLostChildClueRecord).populate(record).execute();
    }

    /**
     * 分页获取失踪儿童线索数据
     * @param paging
     * @return
     */
    public Page<LostChildClueRecord> findLostChildClueRecord(Paging paging) {
        SQLQuery<LostChildClueRecord> query = queryFactory
                .selectFrom(qLostChildClueRecord)
                .orderBy(qLostChildClueRecord.createDate.desc());
        return QueryHelper.queryPage(paging, query);
    }

    /**
     * 获取失踪儿童线索详情
     * @param recordId
     * @return
     */
    public LostChildClueVo getLostChildClueDetail(String recordId){
        if(!StringUtils.hasText(recordId)){
            throw new AppException("recordId为空");
        }

        LostChildClueRecord record = queryFactory.selectFrom(qLostChildClueRecord)
                .where(qLostChildClueRecord.recordId.eq(recordId)).fetchOne();
        if(null == record){
            throw new AppException("未找到相关线索记录");
        }

        LostChild lostChild = this.getLostChildDetail(record.getChildId());
        if(null == lostChild){
            throw new AppException("未找到相关失踪儿童记录");
        }
        LostChildClueVo vo = new LostChildClueVo();
        vo.setLostChild(lostChild);
        vo.setLostChildClueRecord(record);
        return vo;
    }

    public List<LostChild> findChildren(String[] ids) {
        if ((null == ids)
                || (0 == ids.length)) {
            return null;
        }

        return queryFactory.selectFrom(qLostChild)
                .where(qLostChild.id.in(ids))
                .fetch();
    }

    /**
     * 批量插入失踪儿童
     *
     * @author lid
     * @date 2017.12.18
     */
    public void insertInBatch() {
        /*String file = "D:\\失踪儿童数据\\1.json";
        for(int i = 2; i < 11; i ++){
            String number = String.valueOf(i);
            String fileUrl = file.replace("1", number);
            logger.info("批量插入开始");
            String jsonString = FileUtil.ReadFile(fileUrl);

            List<LostChildVo> listVo = (List<LostChildVo>) JSONArray.
                    toList(JSONArray.fromObject(jsonString), LostChildVo.class);

            SQLInsertClause insert = queryFactory.insert(qLostChild);

            for(LostChildVo vo : listVo){
                LostChild lostChild = new LostChild();
                lostChild.setBirthday(vo.getBirthDay());
                lostChild.setCreateDate(new Date());
                lostChild.setCurrentPlace(vo.getCurrentPlace());
                lostChild.setDescription(vo.getDescription());
                lostChild.setHeight(vo.getHeight());
                lostChild.setId(StringUUIdUtil.getUUID());
                lostChild.setMissingDate(vo.getMissingDate());
                lostChild.setName(vo.getName());
                lostChild.setNo(vo.getNO());
                lostChild.setOtherData(vo.getOtherData());
                lostChild.setPhotoUrl(vo.getPhotoUrl());
                lostChild.setSex(vo.getSex());
                lostChild.setType(vo.getType());
                insert.populate(lostChild)
                        .addBatch();
            }
            insert.execute();
            logger.info("完成第"+i+"个!");
        }*/

    }

    public void updateInBatch() {
        String file = "D:\\失踪儿童数据\\1.json";
        for(int i = 1; i < 11; i ++){
            String number = String.valueOf(i);
            String fileUrl = file.replace("1", number);
            logger.info("批量更新开始");
            String jsonString = FileUtil.ReadFile(fileUrl);

            List<LostChildVo> listVo = (List<LostChildVo>) JSONArray.
                    toList(JSONArray.fromObject(jsonString), LostChildVo.class);

            //SQLInsertClause insert = queryFactory.insert(qLostChild);

            SQLUpdateClause update = queryFactory.update(qLostChild);

            for(LostChildVo vo : listVo){
                String missingPlace = vo.getMissingPlace();
                String no = vo.getNO();

                if((!StringUtils.hasText(missingPlace))
                        ||(!StringUtils.hasText(no))){
                    continue;
                }
                update.set(qLostChild.missingPlace, missingPlace)
                        .where(qLostChild.no.eq(no))
                        .addBatch();
            }
            update.execute();
            logger.info("完成第"+i+"个!");
        }

    }

    public Page<LostChild> findChildByNoOrSex(Paging paging, String no, String sex) {
        SQLQuery<LostChild> query = queryFactory.selectFrom(qLostChild);
        if (StringUtils.hasText(sex)) {
            query.where(qLostChild.sex.eq(sex));
        }

        if (StringUtils.hasText(no)) {
            query.where(qLostChild.no.eq(no));
        }
        return QueryHelper.queryPage(paging, query);
    }

    public void deleteLostChild(String id) {
        if (!StringUtils.hasText(id)) {
            throw new AppException("id为空");
        }

        queryFactory.delete(qLostChild)
                .where(qLostChild.id.eq(id))
                .execute();
    }

    public LostChild getLostChildDetail(String id) {
        if (!StringUtils.hasText(id)) {
            throw new AppException("id为空");
        }

        return queryFactory.selectFrom(qLostChild)
                .where(qLostChild.id.eq(id))
                .fetchOne();
    }
}
